package org.example;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo1_JDBC {
    public static void main(String[] args)  {
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try {
            // 1.加载厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取数据库的连接
            connection= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "041106");
            // 3.创建Statement对象
            statement=connection.createStatement();
            // 4.定义SQL并执行SQL语句
            System.out.println("请输入学生姓名：");
            Scanner sc=new Scanner(System.in);
            // 接受用户输入
            String name=sc.next();
            String sql = "select id, name,age, sex from student where name = '" + name + "'";
             // 5.执行SQL,并查询结果
             resultSet=statement.executeQuery(sql);
             //statement.executeUpdate();
             // 6.对结果集进行遍历，获取数据
            while(resultSet.next()){
                int stuId=resultSet.getInt("id");
                String stuName=resultSet.getString("name");
                int stuAge=resultSet.getInt("age");
                String stuSex=resultSet.getString("sex");
                System.out.println(MessageFormat.format("学生编号={0},学生姓名={1},年龄={2},性别={3}",
                        stuId,stuName,stuAge,stuSex));
            }
        }catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            // 依次释放资源，关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
